package com.bole.controller;

import com.bole.data.Result;
import com.bole.dto.article.ArticleTypeDTO;
import com.bole.pojo.TbArticleType;
import com.bole.service.ArticleTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("articleType")
@Api("资源分类管理")
public class ArticleTypeController {

    @Resource
    private ArticleTypeService articleTypeService;

    @GetMapping
    @ApiOperation(value = "获取资讯分类列表",notes = "获取资讯分类列表",tags = "获取资讯分类列表")
    public Result listArticleType() {
        try {
            List<TbArticleType> list = articleTypeService.listArticleType();
            return Result.ok().setData(list);
        } catch (Exception e) {
            return Result.fail().setCode(500).setData("获取资讯分类列表错误");
        }

    }
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ip获取资讯分类",notes = "通过ip获取资讯分类",tags = "通过ip获取资讯分类")
    public Result findArticleTypeById(@PathVariable("id") Integer id) {
        try {
            TbArticleType tbArticleType = articleTypeService.findArticleTypeById(id);
            ArticleTypeDTO articleTypeDTO = new ArticleTypeDTO();
            BeanUtils.copyProperties(tbArticleType,articleTypeDTO);
            return Result.ok().setData(articleTypeDTO);
        } catch (Exception e) {
            return Result.fail().setData("根据id获取资讯错误");
        }
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "修改资讯分类",notes = "修改资讯分类",tags = "修改资讯分类")
    public Result updateArticleType(@PathVariable("id") Integer id,@RequestBody ArticleTypeDTO articleTypeDTO) {
        try {
            articleTypeDTO.setId(id);
            TbArticleType tbArticleType = new TbArticleType();
            BeanUtils.copyProperties(articleTypeDTO,tbArticleType);
            articleTypeService.updateArticleType(tbArticleType);
            return Result.ok().setData("更新成功");
        } catch (Exception e) {
            return Result.fail().setData("更新错误");
        }
    }

    @PostMapping
    @ApiOperation(value = "添加资讯分类",notes = "添加资讯分类",tags = "添加资讯分类")
    public Result saveArticleType(@RequestBody ArticleTypeDTO articleTypeDTO) {
        try {
            TbArticleType tbArticleType = new TbArticleType();
            BeanUtils.copyProperties(articleTypeDTO,tbArticleType);
            articleTypeService.saveArticleType(tbArticleType);
            return Result.ok().setData("增加成功");
        } catch (Exception e) {
            return Result.fail().setData("增加失败");
        }
    }
}
